package com.quanxi.qxaimain.controller.v1.forVueController;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.quanxi.qxaimain.common.globalException.ResponseVo;
import com.quanxi.qxaimain.common.globalException.ResultCode;
import com.quanxi.qxaimain.common.util.RestTemplateUtils.RestTemplateUtils;
import com.quanxi.qxaimain.common.util.sqlFormat.sqlFormat;
import com.quanxi.qxaimain.service.hystrixServer.hystrixServer;
import com.quanxi.qxaimain.service.indicatorsService.indicatorsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lyx
 * @create 2023/4/12 14:37
 */

@Slf4j
@RestController
@RequestMapping("/sqlTest")
@Api(tags = "sql测试")
public class TestSqlController {

    @Resource
    com.quanxi.qxaimain.service.hystrixServer.hystrixServer hystrixServer;
    @Resource
    indicatorsService indicatorsService;


    @ApiOperation(value = "sql测试",  notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ind_id", value = "单个指标唯一编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sql_total", value = "单指标", required = false, dataType = "String"),
            @ApiImplicitParam(name = "total_flag", value = " 0sql 1存储过程  ", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "sql_detail", value = "明细指标", required = false, dataType = "String"),
            @ApiImplicitParam(name = "detail_flag", value = "0sql 1存储过程 ", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "D1", value = "开始时间 YYYY-MM-DD 24hh:mi:ss 2020-1-01 00:00:00", required = true, dataType = "String"),
            @ApiImplicitParam(name = "D2", value = "结束时间 YYYY-MM-DD 24hh:mi:ss 2020-5-01 00:00:00", required = true, dataType = "String") })
    @PostMapping("/sqlTest")
    public Object testsql(@RequestParam String D1,
                              String D2,
                              String sql_total,
                              Integer total_flag,
                              String sql_detail,
                              Integer detail_flag,
                              String ind_id) {



        if(ind_id==null||ind_id.length()==0){
            return  new ResponseVo(ResultCode.VALIDATE_ERROR.getCode(),ResultCode.VALIDATE_ERROR.getMsg(),"ind_id为空");
        }

        // 单sql和明细sql 都为空
        if((sql_total==null||sql_total.length()==0)&&(sql_detail==null||sql_detail.length()==0)){
            return  new ResponseVo(ResultCode.VALIDATE_ERROR.getCode(),ResultCode.VALIDATE_ERROR.getMsg(),"不能空");
        }

        JSONObject jsonObject=new JSONObject();

        //只有单sql
        if((sql_total!=null&&sql_total.length()!=0)&&(sql_detail==null||sql_detail.length()==0)){
            JSONObject  sql_total_test_result = sql_total_test(sql_total, D1, D2, ind_id);
            return sql_total_test_result;
        }
       // 只有明细sql
        if ((sql_detail!=null&&sql_detail.length()!=0)&&(sql_total==null||sql_total.length()==0))
        {
            JSONObject sql_detail_test_result = sql_detail_test(sql_detail, detail_flag, D1, D2, ind_id);
            return  sql_detail_test_result;
        }
        //两者同时存在
        if ((sql_detail!=null&&sql_detail.length()!=0)&&(sql_total!=null&&sql_total.length()!=0))
        {
            JSONObject  sql_total_test_result = sql_total_test(sql_total, D1, D2, ind_id);
            jsonObject.put("sql_value",sql_total_test_result.getString("sql_result"));
            jsonObject.put("sql_time",sql_total_test_result.getString("run_time"));
            jsonObject.put("单sql",sql_total_test_result.getString("sql"));



            JSONObject sql_detail_test_result = sql_detail_test(sql_detail, detail_flag, D1, D2, ind_id);
            jsonObject.put("sql_detail_value",sql_detail_test_result.getString("sql_result"));
            jsonObject.put("sql_detail_time",sql_detail_test_result.getString("run_time"));
            jsonObject.put("明细sql",sql_detail_test_result.getString("sqlformat"));

            return  jsonObject;
        }




        return jsonObject;

    }

private JSONObject sql_total_test(String sql,String D1,String D2,String ind_id ){
    JSONObject jsonObject=new JSONObject();
    String sql_result=null;
    String run_time=null;
    long starTime=System.currentTimeMillis();

   // sql = sqllist.get(0).get("sql_total").toString();

    String sqlformat= sqlFormat.sqlFormat(sql,D1,D2,"");

    JSONObject hystrxSqlresult = hystrixServer.exec_sql_overtime_60s(sqlformat);

    Enum<ResultCode>sql_message =(Enum<ResultCode>) hystrxSqlresult.get("sql_message");

    int code = ((ResultCode) sql_message).getCode();

    if (code==ResultCode.SQL_SUCCESS.getCode()){
        List<LinkedHashMap<String, Object>> linkedHashMaps= (List<LinkedHashMap<String, Object>>) hystrxSqlresult.get("sql_result");
        if (linkedHashMaps.size()>1){
            sql_result="sql失败：返回多行";
        }
        else {
            Map<String, Object> map = linkedHashMaps.get(0);
            Iterator it = map.entrySet().iterator() ;
            while (it.hasNext())
            {
                Map.Entry entry = (Map.Entry) it.next() ;
                Object key = entry.getKey() ;
                Object value = entry.getValue() ;
                if (!key.toString().toLowerCase().equals(ind_id.toLowerCase())){
                    sql_result="sql失败：指标编号与sql返回字段不一致";
                }else {
                    sql_result=map.toString();
                }
            }

        }

    }
    else {
        sql_result=((ResultCode) sql_message).getMsg()+":"+hystrxSqlresult.getString("sql_message_error");
    }


    run_time=(System.currentTimeMillis()-starTime)+"ms";//执行时间
    jsonObject.put("sql_result",sql_result);
    jsonObject.put("ind_id", ind_id  );
    jsonObject.put("sql",sqlformat );
    jsonObject.put("run_time",run_time);

    return  jsonObject;


}

private JSONObject sql_detail_test(String sql,Integer detail_flag,String D1,String D2 ,String ind_id){
    JSONObject jsonObject=new JSONObject();

    if (detail_flag==0){
        jsonObject = indicatorsService.indicatorsDetailSqlTest(sql, D1, D2, "",1,1);

    }
    if (detail_flag==1){
        jsonObject= indicatorsService.indicatorsDetailPorduceTest(sql, D1, D2, "",1,1);

    }
    jsonObject.put("ind_id", ind_id );

    return jsonObject;


}


}